package edu.hrbu.systemadmin.controller;

import edu.hrbu.systemadmin.entity.YdlUser;
import edu.hrbu.systemadmin.service.IYdlUserService;
import edu.hrbu.systemadmin.util.R;
import edu.hrbu.systemadmin.vo.LoginUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 徐登宇
 */
@RestController
@Slf4j
public class IndexController {

    @Resource
    private IYdlUserService ydlUserService;

    // 登录
    @PostMapping("/login")
    public R login(@RequestBody @Validated YdlUser user, BindingResult bindingResult){

        // 处理错误的登录数据
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        if (allErrors.size()>0){
            allErrors.forEach(e-> log.error("{}",e.getDefaultMessage()));
            return R.fail();
        }

        // 进行登录逻辑判断
        LoginUserVo loginUserVo=ydlUserService.login(user.getUserName(), user.getPassword());
        return R.ok(loginUserVo);
    }

    // 登出
    @GetMapping("/logout")
    public R logout(){
        ydlUserService.logout();
        return R.ok();
    }

}
